//
//  NSGCDGroup.m
//  OC_Principle
//
//  Created by wangzhipan on 2025/2/14.
//

#import "NSGCDGroup.h"

@implementation NSGCDGroup

+ (void)setup_enter_leave
{
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_queue_t g_queue = dispatch_get_global_queue(0, 0);
    
    
    /*
     计数机制:
     每次调用 dispatch_group_enter，调度组的计数器增加1。
     每次调用 dispatch_group_leave，计数器减少1。
     当计数器的值为0时，表示所有任务都已完成。
     通知机制:
     可以使用 dispatch_group_notify 来指定在所有任务完成后要执行的操作。这个操作会在计数器变为0时被调用。
     */
    dispatch_group_enter(group);
    dispatch_async(g_queue, ^{
        NSLog(@"Task 1 started");
        [NSThread sleepForTimeInterval:2]; // 模拟延迟
        NSLog(@"Task 1 completed");
        dispatch_group_leave(group);
    });
    
    dispatch_group_enter(group);
    dispatch_async(g_queue, ^{
        NSLog(@"Task 2 started");
        [NSThread sleepForTimeInterval:3]; // 模拟延迟
        NSLog(@"Task 2 completed");
        dispatch_group_leave(group);
    });
    
    dispatch_group_enter(group);
    dispatch_async(g_queue, ^{
        NSLog(@"Task 3 started");
        [NSThread sleepForTimeInterval:4]; // 模拟延迟
        NSLog(@"Task 3 completed");
        dispatch_group_leave(group);
    });
    
    dispatch_group_notify(group, g_queue, ^{
        NSLog(@"All tasks are completed. Updating UI...");
    });
    
}

+ (void)setup_group_async
{
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t g_queue = dispatch_get_global_queue(0, 0);
    dispatch_group_async(group, g_queue, ^{
        NSLog(@"Task 1 started");
        [NSThread sleepForTimeInterval:2]; // 模拟延迟
        NSLog(@"Task 1 completed");
    });
    
    dispatch_group_async(group, g_queue, ^{
        NSLog(@"Task 2 started");
        [NSThread sleepForTimeInterval:3]; // 模拟延迟
        NSLog(@"Task 2 completed");
    });
    
    dispatch_group_async(group, g_queue, ^{
        NSLog(@"Task 3 started");
        [NSThread sleepForTimeInterval:4]; // 模拟延迟
        NSLog(@"Task 3 completed");
    });
    
    dispatch_group_notify(group, g_queue, ^{
        NSLog(@"All tasks are completed. Updating UI...");
    });
}

@end
